package com.example.base.task

import kotlinx.coroutines.*

/**
 * 定时器任务
 * @param initialDelay  启动延时，单位：毫秒
 * @param interval      周期，单位：毫秒
 * @param action        定时器执行内容（次数:Long，当前时间戳:Long）
 *
 */
open class TimerTask(val initialDelay: Long = 10,
                     val interval: Long = 1000,
                     var action: suspend (timer: TimerTask, tick: Tick) -> Unit) : ITask {

    private var dispatcher: CoroutineDispatcher = Dispatchers.Main
    private var running: Boolean = false
    private var startTime: Long = 0L
    private val tick: Tick = Tick()

    private var job: Job = GlobalScope.launch(start = CoroutineStart.LAZY, context = dispatcher) {
        delay(initialDelay)
        while (running) {
            tick.startTime = startTime
            tick.currentTime = System.currentTimeMillis()
            tick.counter++

            action.invoke(this@TimerTask, tick)
            delay(interval)
        }
    }

    /**
     * 设定在子线程上运行
     */
    fun runOnThread(): TimerTask {
        dispatcher = Dispatchers.Default
        return this
    }

    /**
     * 启动Timer
     */
    fun start(): TimerTask {
        stop()

        startTime = System.currentTimeMillis()
        running = true

        job.start()
        return this
    }

    /**
     * 停止Timer
     */
    fun stop() {
        running = false
        job.cancel()
    }

    val isRunning: Boolean
        get() = !job.isCancelled && running

    class Tick {
        var startTime = 0L
        var currentTime = 0L
        var counter = 0L
        override fun toString(): String {
            return "startTime=$startTime, currentTime=$currentTime, counter=$counter"
        }

    }

    private var proxy = object : ITaskProxy {
        override fun start() {
            this@TimerTask.start()
        }

        override fun stop() {
            this@TimerTask.stop()
        }
    }

    override fun getProxy(): ITaskProxy {
        return proxy
    }
}